package 多线程.ThreadLocal;

public class ThreadLocalUseDemo1 {

    private static ThreadLocal<String> threadLocal1 = new ThreadLocal<>();

    private static ThreadLocal<Integer> threadLocal2 = new ThreadLocal<>();


    /**
     * 运行 count个线程,每个线程持有自己独有的 String类型编号
     */
    public void startThreadArray(int count) {
        Thread[] runs = new Thread[count];
        for (int i = 0; i < runs.length; i++) {
            // 赋值编号id
            new ThreadDemo1(i).start();
        }
    }

    /**
     * 线程类：
     */
    public static class ThreadDemo1 extends Thread {

        /**
         * 编号id
         */
        private int codeId;

        public ThreadDemo1(int codeId) {
            this.codeId = codeId;
        }

        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();

            threadLocal1.set("threadLocal1赋值，线程_" + codeId);
            if (codeId == 2) {
                //如果是线程2，设置 threadLocal2变量，值乘以5
                threadLocal2.set(codeId * 5);
            }

            System.out.println(threadName + " -》 " + threadLocal1.get());
            System.out.println(threadName + " -》 " + threadLocal2.get());

            // 使用完移除，help GC
            threadLocal1.remove();
            threadLocal2.remove();
        }
    }

    public static void main(String[] args) {
        ThreadLocalUseDemo1 useDemo = new ThreadLocalUseDemo1();
        // 启动3个线程
        useDemo.startThreadArray(3);
    }

}
